package com.fengye.security.custom.handler;

import com.alibaba.fastjson.JSON;
import com.fengye.common.constants.AppHttpCodeEnum;
import com.fengye.common.domain.ResponseResult;
import com.fengye.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author sunlei
 * @version 1.0
 * @date 2023/9/11 21:23:38
 * @description 授权失败处理器，该接口是在用户已经通过身份验证（即登录），但是尝试访问其权限不足的资源时被调用的
 */
@Slf4j
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        accessDeniedException.printStackTrace();
        log.error("授权失败：{}", accessDeniedException.getMessage());
        // 处理异常
        String json = JSON.toJSONString(ResponseResult.fail(AppHttpCodeEnum.FORBIDDEN).setMessage(accessDeniedException.getMessage()));
        ServletUtils.renderString(response, json);
    }
}
